package cn.itcast.bos.web.action.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;

import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.service.base.AreaService;
import cn.itcast.bos.utils.PinYin4jUtils;
import cn.itcast.bos.web.action.common.BaseAction;
@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class AreaAction extends BaseAction<Area>{
	
	
	//注入service层
	@Autowired
	private AreaService areaService;
	
	//属性驱动 获取上传的文件
	private File file;
	public void setFile(File file) {
		this.file = file;
	}
	
	
	//实现一键上传的功能
	@Action(value="area_batchImport")
	public String batchImport(){
		int count=0;
		List<Area> areas = new ArrayList<Area>();
		HSSFWorkbook hssfWorkBook = null;
		try {
			hssfWorkBook = new HSSFWorkbook(new FileInputStream(file) ); //解析.xls文件
			//读取第一个sheet
			HSSFSheet sheet = hssfWorkBook.getSheetAt(0);
			//读取sheet 工作簿的内容
			for (Row row : sheet) {
				//去掉第一行 标题行
				if(row.getRowNum() == 0){
					continue;
				}
				//如表中间出现空格直接跳过
				//每一行的第一个格为空
				if(row.getCell(0) ==null || StringUtils.isBlank(row.getCell(0).getStringCellValue())){
					continue;
				}
				
				//把数据写入到Area对象中
				Area area = new Area();
				area.setId(row.getCell(0).getStringCellValue());
				area.setProvince(row.getCell(1).getStringCellValue());
				area.setCity(row.getCell(2).getStringCellValue());
				area.setDistrict(row.getCell(3).getStringCellValue());
				area.setPostcode(row.getCell(4).getStringCellValue());
				areas.add(area);
				count++;
				
				//基于pinyin4j的城市编码和简码
				String province = area.getProvince();
				String city = area.getCity();
				String district = area.getDistrict();
				province = province.substring(0,province.length()-1);
				city = city.substring(0,city.length()-1);
				district = district.substring(0,district.length()-1);
				
				//简码
				String[] headArray = PinYin4jUtils.getHeadByString(province+city+district);
				StringBuffer buffer = new StringBuffer();
				for (String string : headArray) {
					buffer.append(string);
				}
				
				String shortcode = buffer.toString();
				area.setShortcode(shortcode);
				
				//城市编码
				String[] citycodes = PinYin4jUtils.stringToPinyin(city);
				String citycode = StringUtils.join(citycodes, "");
				area.setCitycode(citycode);
			}
			
			//优化内存溢出
			if(count>50){
				areaService.saveBatch(areas);
				areas.clear();
				count = 0;
			}
			areaService.saveBatch(areas);
			
		} catch (IOException e) {
			
			e.printStackTrace();
		}finally{
			try {
				//关闭流
				hssfWorkBook.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return NONE;
	}
	
	
	//属性驱动



	//实现分页查询
	@Action(value="area_pageQuery",results={@Result(name="success",type="json")})
	public String pageQuery(){
		Pageable pageable=  new PageRequest(page-1, rows);
		Specification<Area> specification = new Specification<Area>(){
			
			@Override
			public Predicate toPredicate(Root<Area> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> list =  new ArrayList<Predicate>();
				if(StringUtils.isNoneBlank(model.getProvince())){
					Predicate p1 = cb.like(root.get("province").as(String.class), "%"+model.getProvince()+"%");
					list.add(p1);
				}
				if(StringUtils.isNoneBlank(model.getCity())){
					Predicate p2 = cb.like(root.get("city").as(String.class), "%"+model.getCity()+"%");
					list.add(p2);
				}
				if(StringUtils.isNoneBlank(model.getDistrict())){
					Predicate p3 = cb.like(root.get("district").as(String.class), "%"+model.getDistrict()+"%");
					list.add(p3);
				}
				return cb.and(list.toArray(new Predicate[0]));
			}};
			
			Page<Area> pageData = areaService.findPageData(specification,pageable);
			//响应数据封装
			
			pushPageDataToValueStack(pageData);
			
		return SUCCESS;
	}
}
